// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const rightinfoCollection = db.collection('rightinfo')
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let hasInfo
  const school = event.school
  const company = event.company
  const emotion = event.emotion
  const birthday = event.birthday
  const address = event.address
  const chatway = event.chatway 

  await rightinfoCollection.where({
    openid: wxContext.OPENID
  }).get().then(res => {
    hasInfo = res.data.length
  })

  if (hasInfo == 0){
    await rightinfoCollection.add({
      data: {
        openid: wxContext.OPENID,
        createDate: new Date().getTime(),
        modifyDate: new Date().getTime(),
        school,
        schoolState: true,
        company,
        companyState: true,
        emotion,
        emotionState: true,
        birthday,
        birthdayState: true,
        address,
        addressState: true,
        chatway,
        chatwayState: true // 必须可见
        // chatwayDate: new Date().getTime(),
      }
    })
  }else{
    await rightinfoCollection.where({
      openid: wxContext.OPENID
    }).update({
      data: {
        modifyDate: new Date().getTime(),
        school,
        company,
        emotion,
        birthday,
        address,
        chatway
      }
    })
  }

  return {
    event,
    openid: wxContext.OPENID
  }
}